<?php

namespace app\service;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

class MailService
{
    private $config;
    
    public function __construct()
    {
        $this->config = config('mail.smtp');
    }
    
    /**
     * 发送验证码邮件
     */
    public function sendVerificationCode(string $email, string $code, string $type = 'register'): bool
    {
        try {
            $mail = new PHPMailer(true);
            
            // SMTP配置
            $mail->isSMTP();
            $mail->Host = $this->config['host'];
            $mail->SMTPAuth = true;
            $mail->Username = $this->config['username'];
            $mail->Password = $this->config['password'];
            $mail->SMTPSecure = $this->config['encryption'] === 'ssl' ? PHPMailer::ENCRYPTION_SMTPS : PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = $this->config['port'];
            $mail->CharSet = 'UTF-8';
            
            // 设置发件人和收件人
            $mail->setFrom($this->config['from_email'], $this->config['from_name']);
            $mail->addAddress($email);
            
            // 邮件内容
            $subject = $type === 'register' ? '【Find App】注册验证码' : '【Find App】密码重置验证码';
            $mail->Subject = $subject;
            $mail->isHTML(true);
            $mail->Body = $this->buildEmailTemplate($code, $type);
            $mail->AltBody = "您的验证码是：{$code}，有效期10分钟。";
            
            return $mail->send();
            
        } catch (Exception $e) {
            error_log('邮件发送失败: ' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * 构建邮件模板
     */
    private function buildEmailTemplate(string $code, string $type): string
    {
        $title = $type === 'register' ? '注册验证码' : '密码重置验证码';
        
        return "
        <div style='max-width: 600px; margin: 0 auto; font-family: Arial, sans-serif;'>
            <div style='background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; text-align: center;'>
                <h1 style='margin: 0; font-size: 24px;'>{$title}</h1>
            </div>
            <div style='padding: 30px; background: white;'>
                <p style='font-size: 16px; color: #333;'>您好！</p>
                <p style='color: #666;'>您的验证码是：</p>
                <div style='background: #f5f5f5; padding: 20px; text-align: center; margin: 20px 0; border-radius: 8px;'>
                    <span style='font-size: 28px; font-weight: bold; color: #007bff; letter-spacing: 3px;'>{$code}</span>
                </div>
                <p style='color: #999; font-size: 14px;'>验证码有效期为10分钟，请勿泄露给他人。</p>
                <p style='color: #999; font-size: 14px;'>如果您没有进行此操作，请忽略此邮件。</p>
            </div>
            <div style='background: #f8f9fa; padding: 15px; text-align: center; color: #999; font-size: 12px;'>
                <p>此邮件由系统自动发送，请勿回复。</p>
            </div>
        </div>
        ";
    }
}